package com.chuangjiangx.member.manager.basic.web.interceptor;

import com.chuangjiangx.commons.BeanUtils;
import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.member.basic.ddd.domain.model.MbrSourceTerminal;
import com.chuangjiangx.member.basic.ddd.query.MerchantUserInfoQuery;
import com.chuangjiangx.member.basic.ddd.query.dto.UserInfoDTO;
import com.chuangjiangx.member.manager.basic.web.controller.BaseController;
import com.chuangjiangx.member.manager.basic.web.response.Response;
import com.chuangjiangx.member.manager.common.Constants;
import com.chuangjiangx.member.manager.common.ThreadLocalUser;
import com.chuangjiangx.privileges.olddao.dto.MerchantUserCommon;
import com.cloudrelation.partner.platform.model.AgentClientToken;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sun.jmx.snmp.ThreadContext;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 整合WEB和APP登录拦截器
 */
public class LoginInterceptor extends HandlerInterceptorAdapter{


    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private MerchantUserInfoQuery merchantUserInfoQuery;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        boolean isPass = true;
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            Login login = method.getMethodAnnotation(Login.class);
            if (login != null) {

                String tokenStr = request.getHeader(Constants.TOKEN_STR);
                if(!StringUtils.isEmpty(tokenStr)){
                   isPass =  clientLoginInterceptor(tokenStr,response);
                }else{
                   isPass = webLoginInterceptor(request,response);
                }
            }
        }
        return isPass;
    }

    /**
     * 客户端登录拦截
     */
    private boolean clientLoginInterceptor(String tokenStr,HttpServletResponse response) throws Exception{
        ThreadLocalUser user = new ThreadLocalUser();
        AgentClientToken agentClientToken = null;
        if (redisTemplate.opsForValue().get(tokenStr) != null) {
            agentClientToken = JacksonUtils.toObject(objectMapper,redisTemplate.opsForValue().get(tokenStr), AgentClientToken.class);
        }
        if (agentClientToken == null) {
            return returnFalse(response, "未登录");
        }
        //查询登入人信息
        UserInfoDTO userInfoDTO = merchantUserInfoQuery.queryUserInfo(agentClientToken.getMerchantUserId());
        org.springframework.beans.BeanUtils.copyProperties(userInfoDTO,user);
        user.setTerminalNum(agentClientToken.getMacCode());
        //设备类型  1:安卓,2:苹果,3:收银台
        Byte deviceType = agentClientToken.getDeviceType();
        MbrSourceTerminal terminal = ( deviceType == 1 || deviceType == 2 ) ? MbrSourceTerminal.MERCHANT_APP : MbrSourceTerminal.CASHIER_API_TERMINAL;
        user.setTerminalType(terminal.value);
        //在当前线程中存储 AgentClientToken 对象
        ThreadContext.push(Constants.CURRENT_LOGIN_USER_KEY,user);

        return true;
    }

    /**
     * 商户WEB登录拦截
     */
    private boolean webLoginInterceptor(HttpServletRequest request, HttpServletResponse response)throws  Exception{
        ThreadLocalUser user = new ThreadLocalUser();
        MerchantUserCommon merchantUserCommon = (MerchantUserCommon) request.getSession().getAttribute(BaseController.SESSION_USER);
        if(null == merchantUserCommon){
            return returnFalse(response, "未登录");
        }
        BeanUtils.convertBean(merchantUserCommon,user);
        if (merchantUserCommon == null) {
            return returnFalse(response, "未登录");
        }else{
            //查询登入人信息
            UserInfoDTO userInfoDTO = merchantUserInfoQuery.queryUserInfo(merchantUserCommon.getId());
            org.springframework.beans.BeanUtils.copyProperties(userInfoDTO,user);
            ThreadContext.push(Constants.CURRENT_LOGIN_USER_KEY,user);
            return true;
        }
    }

    /**
     * 未登录抛异常
     */
    private  Boolean returnFalse(HttpServletResponse response, String errMsg) throws Exception {

        Response resp = new Response();
        resp.setErr_code("000006");
        resp.setErr_msg(errMsg);
        resp.setSuccess(false);
        response.getWriter().println(JacksonUtils.toJson(objectMapper,resp));
        return false;
    }

}
